package storm.Data.DataRule;

import java.util.Iterator;

import storm.Entity;
import storm.Timer;
import storm.Data.Data;

public class LateRessource extends Entity  implements Icontrol {

	
	public Data data;

	boolean ready;
	public boolean master=false;
	LateRessource MasterData=null;
	String groupe="";
	int latence;
	private boolean readyAndOk=false;
	public Data getData() {
		return data;
		
	
	}

	public void setData(Data data) {
		this.data = data;
		this.ready = false;
		

	
	
		
		
	}

	public void isConsume() {
		//this.data.setRate(this.data.getRate() +1);
		// TODO Auto-generated method stub
		this.readyAndOk = false;
		ready = false;

	}
	public void atTimer(){
		this.readyAndOk = true;
	}
	public void isProduct() {
	/*	if (this.master) this.readyAndOk = true;
		else {*/
		//	int latence  = this.MasterData.getLatence(this.data.getOwnFieldIntValue("latency"));
		
		//System.out.println(this.data.Kernel.getTime());
		
		Timer timer;
		if (this.latence > 0 ) {
			timer = new Timer ("atTimer",this.latence,this);
			this.data.getKernel().addTimer(timer);
		}
		else this.readyAndOk = true;
		
			
		//}
		// TODO Auto-generated method stub
		//this.readyAndOk = true;
		ready = true;
	}
	private int getLatence(int ownFieldIntValue) {
		this.latence = this.latence + ownFieldIntValue;
		// TODO Auto-generated method stub
		return this.latence;
	}

	public boolean isAvailableToDestination() {
	
		return (this.readyAndOk);
	}
	public boolean hasToBlockDestination() {
	//	System.out.println(this.data.Kernel.getTime() + "  " + this.ready);
		
		return !(this.readyAndOk);
	}

	public void init() {
		//Parcours des autres data pour savoir si une data appartient au m?me groupe
		// TODO Auto-generated method stub
		this.groupe=this.data.getOwnFieldStringValue("groupe");
		//System.out.println(" ****** "  + this + " -----"  + this.data + " ---" + this.data.getKernel());
		Iterator I = this.data.getKernel().getlisteEntities().iterator();
		this.latence = this.data.getOwnFieldIntValue("latency");
		while (I.hasNext()){
			Object O = I.next();
			if (O instanceof Data){
			
				Data D = (Data) O;
				if (D.getControlRule() instanceof LateRessource ){
					if (  (  ( (LateRessource)D.getControlRule()).master )  
								&&  (((LateRessource)D.getControlRule()).groupe.equalsIgnoreCase(this.groupe) )  ) {
						
						this.MasterData = ((LateRessource)D.getControlRule());
						
					//	System.out.println(this + " --Master - " + D.getControlRule());
					}
					
					
				}
				
			}
		}
		if (this.MasterData == null ) {
			this.master = true;
			
			this.MasterData = this;
		}
		
	}
	public Icontrol clone(){
		return (Icontrol) super.clone();

	}

	
	
}